How to Round Off Numbers in R

Although R can calculate accurately to up to 16 digits, you don’t always want to use that many digits. In this case, you can use a couple functions in R to round numbers. To round a number to two digits after the decimal point, for example, use the round() function as follows:

> round(123.456,digits=2)
[1] 123.46

You also can use the round() function to round numbers to multiples of 10, 100, and so on. For that, you just add a negative number as the digits argument:

> round(-123.456,digits=-2)
[1] -100

If you want to specify the number of significant digits to be retained, regardless of the size of the number, you use the signif() function instead:

> signif(-123.456,digits=4)
[1] -123.5

Both round() and signif() round numbers to the nearest possibility. So, if the first digit that’s dropped is smaller than 5, the number is rounded down. If it’s bigger than 5, the number is rounded up.

If the first digit that is dropped is exactly 5, R uses a rule that’s common in programming languages: Always round to the nearest even number. round(1.5) and round(2.5) both return 2, for example, and round(-4.5) returns -4.

Contrary to round(), three other functions always round in the same direction: